﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Telerik.WinControls;
using Telerik.WinControls.UI;
using Aspose.Cells;
using System.IO;

namespace UnigenReport.Form
{
    public partial class ucShipAddress : UserControl
    {
        private UnigenDataContext db;

        #region Thiết lập

        public ucShipAddress()
        {
            InitializeComponent();
            //Phân quyền
            if (Variables.UserRoleID == 0)
            {
                btnDelete.Visibility =
                btnImport.Visibility =
                btnExportTemp.Visibility = ElementVisibility.Collapsed;
            }
            SetEvent();
            Common.SetMenuShortcut(btnInsert, btnUpdate, btnDelete, btnGetData, btnCloseForm);
        }

        /// <summary>
        /// Khai báo các sự kiện
        /// </summary>
        private void SetEvent()
        {
            this.Load += OnLoad;
            this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
            this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            this.btnGetData.Click += new System.EventHandler(this.btnGetData_Click);
            this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
            this.btnExportTemp.Click += new System.EventHandler(this.btnExportTemp_Click);
            this.btnCloseForm.Click += new System.EventHandler(this.btnCloseForm_Click);
            this.btnSaveImport.Click += new System.EventHandler(this.btnSaveImport_Click);
            this.btnCancelImport.Click += new System.EventHandler(this.btnCancelImport_Click);
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            this.grvShipAddress.CellDoubleClick += new Telerik.WinControls.UI.GridViewCellEventHandler(this.grvShipAddress_CellDoubleClick);        
        }

        /// <summary>
        /// Hàm load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoad(object sender, EventArgs e)
        {
            //Load default
            SetDefault();
        }

        /// <summary>
        /// Thiết lập các giá trị mặc định của form
        /// </summary>
        private void SetDefault()
        {
            //Source type
            var dtbType = new DataTable();
            dtbType.Columns.Add("Id");
            dtbType.Columns.Add("Name");
            dtbType.Rows.Add(0, "BILL TO");
            dtbType.Rows.Add(1, "SHIP TO");

            sourceType.DataSource = dtbType;

            //Bind dữ liệu chính
            BindData();
        }

        /// <summary>
        /// Lấy dữ liệu chính
        /// </summary>
        private void BindData()
        {
            //Data bind
            db = new UnigenDataContext();
            var name = txtName.Text.Trim();
            sourceShipAddress.DataSource = db.ShipAddresses.Where(p => p.Active == true 
                && (!String.IsNullOrEmpty(name) ? p.Name.Contains(name) : 1==1)
                ).OrderBy(p=>p.Type).ThenBy(p => p.Name).ToList();

            //STT
            Common.SetNo(grvShipAddress);
        }

        #endregion

        #region Hàm

        private void Insert()
        {
            try
            {
                var newItem = new Form.ucShipAddressEdit() { Dock = DockStyle.Fill };
                var ui = Common.CreateForm(newItem, String.Empty, 460, 390);

                if (ui.ShowDialog() == DialogResult.OK)
                {
                    BindData();
                    Common.ShowSaveSuccess();
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Insert - " + ex.Message);
            }
        }

        private void Update()
        {
            try
            {
                if (sourceShipAddress.Current == null)
                {
                    Common.ShowSelectionRequire();
                    return;
                }

                var p = sourceShipAddress.Current as ShipAddress;

                var itemEdit = new Form.ucShipAddressEdit() { Dock = DockStyle.Fill }.ForUpdate(p);
                var ui = Common.CreateForm(itemEdit, String.Empty, 460, 390);

                if (ui.ShowDialog() == DialogResult.OK)
                {
                    BindData();
                    Common.ShowSaveSuccess();
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Update - " + ex.Message);
            }
        }

        private void Delete()
        {
            try
            {
                if(Common.ShowQuestion("Xóa dòng này?") != DialogResult.OK)
                    return;

                if (sourceShipAddress.Current == null)
                {
                    Common.ShowSelectionRequire();
                    return;
                }

                db = new UnigenDataContext();
                var inputItem = (sourceShipAddress.Current as ShipAddress);
                var removeItem = db.ShipAddresses.SingleOrDefault(p => p.ShipAddressId == inputItem.ShipAddressId);
                //Xóa
                db.ShipAddresses.DeleteOnSubmit(removeItem);
                db.SubmitChanges();

                //Remove khỏi grid
                sourceShipAddress.Remove(inputItem);
                Common.SetNo(grvShipAddress);

                //Thông báo
                Common.ShowSaveSuccess();
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Delete - " + ex.Message);
            }
        }

        private void SetImportState(bool isImport)
        {
            if (isImport)
            {
                cmbImport.Visibility = ElementVisibility.Visible;
                cmbMenu.Enabled = btnSearch.Enabled = txtName.Enabled = false;
                grvShipAddress.CellDoubleClick -= grvShipAddress_CellDoubleClick;
            }
            else
            {
                cmbImport.Visibility = ElementVisibility.Collapsed;
                cmbMenu.Enabled = btnSearch.Enabled = txtName.Enabled = true;
                grvShipAddress.CellDoubleClick += grvShipAddress_CellDoubleClick;
            }
        }

        #endregion
        
        #region Sự kiện

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                BindData();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            Insert();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Update();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            //Chon file
            var openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (openFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = openFileDialog.FileName;

            //Import
            var workbook = new Workbook(fileName);
            var woCells = workbook.Worksheets[0].Cells;

            var lstImportSA = new List<ShipAddress>();
            var success = true;
            var row = 2;
            var error = String.Empty;
            while (woCells["B" + row].Value != null)
            {
                var sa = new ShipAddress();
                sa.Type = 1;
                sa.Name = (woCells["B" + row].Value ?? "").ToString();
                sa.Address = (woCells["C" + row].Value ?? "").ToString();
                sa.Phone = (woCells["D" + row].Value ?? "").ToString();
                sa.Fax = (woCells["E" + row].Value ?? "").ToString();
                sa.Active = true;

                //Add to list
                lstImportSA.Add(sa);

                row++;
            }
            if (!success)
            {
                Common.ShowErrorMess(error);
            }
            else
            {
                SetImportState(true);
                sourceShipAddress.Clear();
                sourceShipAddress.DataSource = lstImportSA;
                Common.SetNo(grvShipAddress);
            }
        }

        private void btnExportTemp_Click(object sender, EventArgs e)
        {
            //Xuat file
            var saveFileDialog = new SaveFileDialog
            {
                FileName = "ShipAddressTemplate.xls"
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (saveFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = saveFileDialog.FileName;

            //Mở file template cần đổ dữ liệu vào
            var stream = new MemoryStream(global::UnigenReport.Properties.Resources.ShipAddressTemplate);
            //Tạo một đối tượng workbook
            var workbook = new Workbook(stream);

            workbook.Save(fileName);

            //Mở file Excel vừa lưu
            System.Diagnostics.Process.Start(fileName);
        }

        private void btnCloseForm_Click(object sender, EventArgs e)
        {
            (this.Parent as Telerik.WinControls.UI.RadPageViewPage).Dispose();
        }

        private void btnSaveImport_Click(object sender, EventArgs e)
        {
            if (sourceShipAddress.Count == 0)
            {
                Common.ShowNoticeMess("Không có dữ liệu mới!");
                SetImportState(false);
                BindData();
                return;
            }

            db = new UnigenDataContext();
            foreach (var item in (sourceShipAddress.DataSource as List<ShipAddress>))
                db.ShipAddresses.InsertOnSubmit(item.Clone());

            db.SubmitChanges();
            BindData();
            //menu
            SetImportState(false);
        }

        private void btnCancelImport_Click(object sender, EventArgs e)
        {
            BindData();
            //menu
            SetImportState(false);
        }
        
        private void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void grvShipAddress_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            Update();
        }

        #endregion
    }
}
